#include "PhnqletManager.h"
#include "Environment.h"
#include "StaticFileCommand.h"
#include <iostream>
#include <vector>
#include <dirent.h>
#include <string.h>

namespace phnq
{
	namespace phnqlets
	{
		void scan(vector<string> &dirs, const char *parent, const char *name)
		{
			char path[256];
			sprintf(path, "%s/%s", parent, name);
		
			DIR *dir = opendir(path);
			if(dir)
			{
				struct dirent *pent;
				while(pent = readdir(dir))
				{
					if(strcmp(pent->d_name, ".") && strcmp(pent->d_name, ".."))
						scan(dirs, path, pent->d_name);
				}
				closedir(dir);
			}
			else // path represents a file
			{
				if(strcmp(name, "config.xml") == 0)
					dirs.push_back(parent);
			}
		}
	
		PhnqletManager::PhnqletManager()
		{
			vector<string> dirs;
		
			vector<string> resPaths = Environment::getInstance()->getResourcePaths();
		
			for(int i=0; i<resPaths.size(); i++)
			{
				string s = resPaths[i];
				scan(dirs, s.c_str(), "phnqlets");
			}
		
			for(int i=0; i<dirs.size(); i++)
			{
				StaticFileCommand::addForbiddenPath(dirs[i]);
				
				Phnqlet *p = new Phnqlet(dirs[i]);
				string type = p->getType();
				string alias = p->getAlias();
				if(!phnqlets[type])
				{
					phnqlets[type] = phnqletsByIndex[p->getIndex()] = p;
					if(alias != "")
						phnqlets[alias] = phnqlets[type];
				}
			}
		}

		PhnqletManager* PhnqletManager::getInstance()
		{
			static PhnqletManager instance;
		
			return &instance;
		}
	
		Phnqlet* PhnqletManager::get(string type)
		{
			return phnqlets[type];
		}
	
		Phnqlet* PhnqletManager::get(int idx)
		{
			return phnqletsByIndex[idx];
		}
	}
}
